<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Video Stream Processing with Socket.IO</title>
    <!-- 引入Socket.IO客户端库 -->
    <script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
</head>

<body>
<!-- <video id="video" width="256" height="192" style="display:none;"></video> -->
<video id="video" width="256" height="192"></video>
<canvas id="canvas" width="256" height="192" style="display:none;"></canvas>
<img id="processed-img" alt="Processed Image" width="256" height="192">
<script>
    const video = document.getElementById('video');
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    const processedImg = document.getElementById('processed-img');

    // 连接到Socket.IO服务器
    const socket = io('http://localhost:12138'); // 确保这是您的Socket.IO服务器URL

    navigator.mediaDevices.getUserMedia({video: true})
        .then(stream => {
            video.srcObject = stream;
            video.play();
            let frameCount = 0;
            const captureInterval = 60;
            async function captureAndSend() {
                // 清除 Canvas
                // ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                // 将Canvas图像数据转换为Blob
                canvas.toBlob(blob => {
                    frameCount++;
                    if (blob) {
                        // 发送Blob数据到后端（更高效的方式）
                        if (frameCount % captureInterval === 0) {
                            const reader = new FileReader();
                            reader.onloadend = () => {
                                if (reader.error) {
                                    console.error('读取Blob数据时出错:', reader.error);
                                } else {
                                    socket.emit('video_frame', reader.result);
                                }
                            };
                            reader.onerror = () => {
                                console.error('读取Blob数据时出错:', reader.error);
                            };
                            reader.readAsArrayBuffer(blob);
                        } else {
                            const objectURL = URL.createObjectURL(blob);
                            processedImg.src = objectURL;
                            processedImg.onload = () => {
                                // 图片加载完成后释放 URL
                                URL.revokeObjectURL(objectURL);
                            };
                            processedImg.onerror = () => {
                                console.error('图片加载失败');
                                URL.revokeObjectURL(objectURL);
                            };
                        }
                    } else {
                        console.error('无法将Canvas转换为Blob');
                    }
                }, 'image/png')
                // 设置下一帧的捕获
                requestAnimationFrame(captureAndSend);
            }

            // 开始捕获和发送视频帧
            requestAnimationFrame(captureAndSend);

            // 监听来自后端的消息
            socket.on('processed-image', event => {
                // 假设后端返回的是ArrayBuffer，我们需要将其转换为DataURL
                // const data = event.data;
                // console.log(event)
                // const blob = new Blob([arrayBuffer], { type: 'image/png' });
                // const url = URL.createObjectURL(event);
                processedImg.src = event.image;

                // 可选：释放URL对象（在不再需要图像时）
                // URL.revokeObjectURL(url);
                // processedImg.src = data
            });

            socket.on('disconnect', event => {
                console.log('Socket.IO connection closed:', event);
            });

            socket.on('error', event => {
                console.error('Socket.IO error:', event);
            });
        })
        .catch(error => console.error('Error accessing media devices.', error));
</script>
</body>

</html>